<template>
  <div class="app-container">

    <u-page title="仓位维护">

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="楼层" prop="floor">
            <el-select v-model="listQuery.floor" placeholder="请选择楼层" clearable>
              <el-option v-for="item in floors" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库" prop="roomid">
            <el-cascader ref="whList" v-model="listQuery.roomid" :options="whrooms" clearable :show-all-levels="false" @change="handleWhChanged" />
          </el-form-item>
          <el-form-item label="所属课室" prop="blongdeptid">
            <!--            <el-select v-model="listQuery.blongdeptid" placeholder="请选择部门" clearable>-->
            <!--              <el-option v-for="item in departments" :label="item.deptname" :value="item.deptid" />-->
            <!--            </el-select>-->
            <el-cascader
              ref="depts"
              v-model="listQuery.blongdeptid"
              :options="departments"
              :show-all-levels="false"
              @change="handleQuerydeptChanged"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" @click="hdlOpen">
              {{ textMap['create'] }}
            </el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-if="row.status===1" type="text" @click="hdlGrantKey(row)">发放钥匙</el-button>
              <el-button v-if="row.status>1" type="text" @click="hdlReturnkey(row)">归还钥匙</el-button>
              <el-button type="text" @click="hdlEdit(row)">编辑</el-button>
              <el-button type="text" @click="hdlDelete(row.id, row.roomname)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>
    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" width="600px" @confirm="dialogStatus==='create'? hdlCreate():hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-width="100px">
        <el-row>
          <el-form-item prop="floor" label="楼层" v-if="false">
            <el-input v-model="dataForm.floor" placeholder="请填写楼层" clearable />
          </el-form-item>
          <el-form-item prop="roomid" label="仓库">
            <el-cascader ref="whroomList" v-model="dataForm.roomid" :options="whrooms" :show-all-levels="false" @change="handleWhroomChanged" />
          </el-form-item>
          <el-form-item prop="sitename" label="仓位名">
            <el-input v-model="dataForm.sitename" placeholder="请填写仓位名" clearable />
          </el-form-item>
          <el-form-item prop="square" label="面积">
            <el-input v-model="dataForm.square" placeholder="仅允许数字和两位小数" clearable @input="handleNumberInput('square', 2)" />
          </el-form-item>
          <el-form-item prop="monthrent" label="参考月租金">
            <el-input v-model="dataForm.monthrent" placeholder="仅允许数字和两位小数" clearable @input="handleNumberInput('monthrent', 2)" />
          </el-form-item>
          <el-form-item prop="dayrent" label="参考日租金">
            <el-input v-model="dataForm.dayrent" placeholder="仅允许数字和两位小数" clearable @input="handleNumberInput('dayrent', 2)" />
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <textarea v-model="dataForm.remark" style="width:80%;height: 150px;" />
          </el-form-item>
          <el-form-item label="是否可租" prop="rentable">
            <el-radio-group v-model="dataForm.rentable">
              <el-radio :label="0">可租</el-radio>
              <el-radio :label="1">不可租</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
    </u-dialog>
    <u-dialog title="时间确认" :show.sync="dialogGrantFormVisible" :footer="true" width="400px" @confirm="ReturnKey()" @cancel="handleDialogCancel">
      <el-form ref="dialogGrantForm" :model="GrantForm" label-width="100px">
        <el-form-item label="关联表单" prop="formcode">
          <el-input v-model="GrantForm.formcode" style="width: 200px" :rules="{required: true, message: '请填写表单号以便核算超期费用', trigger: 'change' }"/>
        </el-form-item>
        <el-form-item label="归还时间" prop="returnDate" :rules="{required: true, message: '请选择归还时间', trigger: 'change' }">
          <el-date-picker
            v-model="GrantForm.returnDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
    </u-dialog>
  </div>
</template>
<script>

export default {
  data() {
    return {
      api: this.$u.api.OpcenWhsite,
      dataapi: this.$u.api.OpcenMaintain,
      htapt: this.$u.api.ContractWhapply,
      // 楼层
      floors: [],
      departments: [],
      whrooms: [],
      textMap: {
        update: '编辑仓位',
        create: '新增仓位'
      },
      dialogFormVisible: false,
      dialogGrantFormVisible: false,
      dialogStatus: '',
      rules: {
        roomid: [
          { required: true, message: '请选择仓库', trigger: ['change'] }
        ],
        sitename: [
          { required: true, message: '请填写仓位名称', trigger: ['blur'] }
        ],
        monthrent: [
          { required: true, message: '请填写月租金', trigger: ['blur'] }
        ],
        dayrent: [
          { required: true, message: '请填写日租金', trigger: ['blur'] }
        ]
      },
      listOptions: {
        mutiSelect: true,
        stripe: true
      },
      listLoading: false,
      list: [],
      // 表格
      columns: [
        {
          prop: 'floor',
          label: '楼层',
          sortable: true
        },
        {
          prop: 'roomname',
          label: '仓库名称'
        },
        {
          prop: 'sitename',
          label: '仓位名'
        },
        {
          prop: 'square',
          label: '面积'
        },
        {
          prop: 'monthrent',
          label: '参考月租金'
        },
        {
          prop: 'dayrent',
          label: '参考日租金'
        },
        {
          prop: 'remark',
          label: '备注'
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status === 0) {
              return h('el-tag', { props: { type: 'success' }}, '空闲')
            } else if (params.row.status === 1) {
              return h('el-tag', { props: { type: 'warning' }}, '申请中')
            } else if (params.row.status === 2) {
              return h('el-tag', { props: { type: 'danger' }}, '占用')
            } else if (params.row.status === 3) {
              return h('el-tag', { props: { type: 'info' }}, '停用')
            } else if (params.row.status === 4) {
              return h('el-tag', { props: { type: '' }}, '超期')
            }
          }
        },
        {
          prop: 'blongdeptname',
          label: '所属课室'
        },
        {
          prop: 'createdby',
          label: '创建人'
        },
        {
          prop: 'createdAt',
          label: '创建时间',
          sortable: true,
          timestamp: true
        }
      ],
      listQuery: {
        page: 1,
        pageSize: 20,
        totalCount: 1,
        roomid: '',
        floor: '',
        blongdeptid: ''
      },
      GrantForm: {},
      pickerTime: '',
      // 选择的row
      pickRow: {}
    }
  },
  mounted() {
    this.getFloors()
    this.getDepartments()
    this.getWhrooms()
  },
  methods: {
    // 加载楼层
    getFloors() {
      const self = this
      self.dataapi.floors().then(res => {
        this.floors = res.data
      })
    },
    getWhrooms() {
      const self = this
      self.api.whroomtree().then(res => {
        this.whrooms = res.data
      })
    },
    // 加载部门
    getDepartments() {
      const self = this
      self.dataapi.deptList().then(res => {
        this.departments = res.data
      })
    },
    // 选择课室功能
    handleDeptId() {
      let obj = {}
      obj = this.departments.find((item) => item.deptid === this.dataForm.blongdeptid)
      this.dataForm.blongdeptname = obj.deptname
    },
    handleQuerydeptChanged() {
      const self = this
      self.listQuery.deptname = this.$refs['depts'].getCheckedNodes()[0].label
      self.listQuery.deptid = this.$refs['depts'].getCheckedNodes()[0].value
    },
    // 选择仓库
    handleWhroomChanged() {
      const self = this
      self.dataForm.roomid = this.$refs['whroomList'].getCheckedNodes()[0].value
      self.dataForm.floor = this.$refs['whroomList'].getCheckedNodes()[0].parent.value
    },
    handleWhChanged() {
      const self = this
      self.listQuery.roomid = this.$refs['whList'].getCheckedNodes()[0].value
    },
    handleFilter() {
      this.hdlFilter()
    },
    // 发放钥匙
    hdlGrantKey(row) {
      const self = this
      // 模态对话框组件
      // self.$confirm('此操作将发放钥匙开始租用仓库，是否继续发放？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
      //   // 处理确认事件
      //   self.api.grantkey(row).then(() => {
      //     // 刷新数据列表
      //     self.hdlList()
      //     // 通知信息
      //     self.$u.msg('发放成功')
      //   })
      // }).catch(() => {
      // })
      self.$prompt('请输入csms申请单号', '单号确认', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          // 必填校验逻辑
          if (!value || value.trim() === '') {
            return '内容不能为空'
          }
          return true // 验证通过
        },
        inputErrorMessage: '请输入有效内容' // 错误提示
      }).then(({ value }) => {
        row.formcode = value
        self.htapt.grantkey(row).then(res => {
          // 通知信息
          self.$u.msg(res.data)
          // 刷新数据列表
          self.hdlList()
        })
      }).catch(() => {
        row.formcode = ''
      })
    },
    // 归还钥匙
    hdlReturnkey(row) {
      const self = this
      self.dialogGrantFormVisible = true
      self.pickRow = row
    },
    // 归还钥匙
    ReturnKey() {
      const self = this
      self.pickRow.returnDate = self.GrantForm.returnDate
      self.pickRow.formcode = self.GrantForm.formcode
      self.htapt.returnkey(self.pickRow).then(res => {
        // 通知信息
        self.$u.msg(res.data)
        // 刷新数据列表
        self.hdlList()
      })
    },
    handleDialogCancel() {
      const self = this
      self.GrantForm = { returnDate: null } // 重置数据
      self.dialogGrantFormVisible = false
    },
    // 实时输入过滤
    handleNumberInput(field, decimalCount) {
      let val = this.dataForm[field]
      // 过滤非法字符（保留数字和小数点）
      val = val.replace(/[^0-9.]/g, '')
      // 处理多个小数点
      val = val.replace(/\.{2,}/g, '.')
      // 限制小数点后位数
      const dotIndex = val.indexOf('.')
      if (dotIndex !== -1 && val.length - dotIndex > decimalCount + 1) {
        val = val.substring(0, dotIndex + decimalCount + 1)
      }
      this.dataForm[field] = val
    }
  }
}
</script>
<style>
.el-select .el-input {
  width: 220px;
}
</style>
<style lang="scss" scoped>
.app-container {
}
</style>
